#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import tarfile
import yaml

def tar(filelist, path_name):
    tf = tarfile.open(path_name, "w:gz")

    for file_name in filelist:
        tf.add(file_name)

    tf.close()

def get_config(file_name):
    """
    解析yaml
    return dict
    """
    if not os.path.exists(file_name):
        return {}

    with open(file_name, "r") as f:
        return yaml.load(f)

def send_mail(mail, title, send_str, files, del_file=True):
    sender = mail.get('sender', '')
    receiver = mail.get('receiver', [])
    server = mail.get('SMTP_server', '')
    port = mail.get('SMTP_port', 465)
    password = mail.get('password', '')

    msg = MIMEMultipart()
    msg['Subject'] = Header(title, 'utf-8')
    msg['From'] = 'server<%s>' %sender
    msg['To'] = ';'.join(receiver)
    msg.attach(MIMEText(send_str, 'plain', 'utf-8'))

    #add attachment
    for path in files:
        if not os.path.isfile(path):
            continue
        attachment = MIMEApplication(open(path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='{0}'.format(os.path.basename(path)))
        msg.attach(attachment)
        del_file and os.remove(path)

    try:
        #smtp = smtplib.SMTP()
        #smtp.connect(server)
        smtp = smtplib.SMTP_SSL(server, port)
        smtp.login(sender, password)
        smtp.sendmail(sender, receiver, msg.as_string())
    except Exception as e:
        print("send mail to %s error!" % ";".join(receiver))
        print(e)
    smtp.quit()

